package com.lanou3g.bookstore.cart.web.servlet;

import com.lanou3g.bookstore.book.domain.Book;
import com.lanou3g.bookstore.book.service.BookService;
import com.lanou3g.bookstore.cart.domain.Cart;
import com.lanou3g.bookstore.cart.domain.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "CartServlet", urlPatterns = "/cart.do")
public class CartServlet extends HttpServlet {
    private BookService bookService = new BookService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bid = request.getParameter("bid");
        String count = request.getParameter("count");
        if (bid == null) {//bid不存在表示清空购物车
            Cart cart = (Cart) request.getSession().getAttribute("cart");
            Map<String, CartItem> cartItems = cart.getCartItemMap();
            cartItems.clear();
        } else {
            Cart cart = (Cart) request.getSession().getAttribute("cart");
            if (cart == null) {//cart不存在去登录
                response.sendRedirect(request.getContextPath() +
                        "/jsps/user/login.jsp");
                return;
            }
            if (count == null) {//count不存在表示要删除购物车中的一个信息
                Map<String, CartItem> cartItems = cart.getCartItemMap();
                cartItems.remove(bid);
            } else {//count存在表示要向购物车添加信息
                Book book = bookService.load(bid);//获取图书信息
                CartItem cartItem = new CartItem();
                cartItem.setBook(book)
                        .setCount(Integer.valueOf(count));
                Map<String, CartItem> cartItems = cart.getCartItemMap();
                cartItems.put(bid, cartItem);
            }
        }
        response.sendRedirect(request.getContextPath()
                + "/jsps/cart/list.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
